package com.hl.manage.controller;


import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hl.manage.entity.Department;
import com.hl.manage.entity.User;
import com.hl.manage.service.IDepartmentService;
import com.hl.manage.service.IUserService;
import com.hl.manage.utils.SendResult;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Helei
 * @since 2021-03-15
 */
@RestController
@RequestMapping("/manage/department")
public class DepartmentController {
	@Autowired
	private IDepartmentService iService;
	@Autowired
	private IUserService user;
	
	/**
	 * 根据登录的用户权限查看公司和部门
	 * @param request
	 * @return
	 */
	@RequestMapping("/getall")
	public String getAll(HttpServletRequest request) {
		HttpSession session = request.getSession();
		QueryWrapper<User> qWrapper = Wrappers.query();
		qWrapper.eq("account",session.getAttribute("account"));
		User userres = user.getOne(qWrapper);
		if(userres==null){
			SendResult sendResult = new SendResult();
			sendResult.setCode(400001);
			sendResult.setMsg("当前用户未分配公司");
			sendResult.setData(null);
			return sendResult.toString();
		}
		List<String> list = new ArrayList<String>();
		Department department =  iService.getById(userres.getCompanyId());
		System.out.println(department.toString());
			JSONObject jsonObj = JSON.parseObject(department.toString());
			List<Department> listde  = iService.findByParentId(department.getId());
			List<String> listitem = new ArrayList<String>();
			for (Department department2 : listde) {
				JSONObject jsonitem = JSON.parseObject(department2.toString());
				jsonitem.put("children", iService.findByParentId(department2.getId()));
				listitem.add(jsonitem.toJSONString());
			}
			jsonObj.put("children", listitem.toString());
			list.add(jsonObj.toJSONString());
		SendResult sendResult = new SendResult();
		sendResult.setCode(200);
		sendResult.setMsg("查询成功");
		sendResult.setData(list.toString());
		return sendResult.toString();
	}
	
	@RequestMapping("/saveorupdate")
	public String updateOrSave(@Param("params") String params) throws UnsupportedEncodingException {
		SendResult sendResult = new SendResult();
		JSONObject jsonObject = JSONObject.parseObject(URLDecoder.decode(params.replaceAll("%25", ""), "UTF-8"));
		Department department = new Department();
		if (jsonObject.get("id").toString().isEmpty()) {
			department.setId(null);
		}else {
			department.setId(Integer.parseInt(jsonObject.get("id").toString()));
			List<Department> lDepartments =  iService.findByParentId(Integer.parseInt(jsonObject.get("id").toString()));
			if (!lDepartments.isEmpty()&&jsonObject.get("type").toString().equals("1")) {
				sendResult.setCode(400001);
				sendResult.setMsg("当前公司有下级部门，不允许修改为部门");
				sendResult.setData(null);
				return sendResult.toString();
			}
		}
		department.setType(Integer.parseInt(jsonObject.get("type").toString()));
		department.setName(jsonObject.get("name").toString());
		department.setOrdernum(Integer.parseInt(jsonObject.get("order").toString()));
		department.setParentId(Integer.parseInt(jsonObject.get("parentId").toString()));
		
		
		if(iService.saveOrUpdate(department)) {
			sendResult.setCode(200);
			sendResult.setMsg("操作成功");
			sendResult.setData(null);
		}else {
			sendResult.setCode(400001);
			sendResult.setMsg("操作失败");
			sendResult.setData(null);
		}
		return sendResult.toString();
	}
	@RequestMapping("delbyid")
	public String delById(@Param("id") Integer id){
		SendResult sendResult = new SendResult();
		List<Department> department = iService.findByParentId(id);
		if (id==1) {
			sendResult.setCode(400001);
			sendResult.setMsg("删除失败，顶级公司不可删除");
			sendResult.setData(null);
			return sendResult.toString();
		}
		if(department.isEmpty()) {
			if(iService.removeById(id)) {
				sendResult.setCode(200);
				sendResult.setMsg("删除成功");
				sendResult.setData(null);
			}else {
				sendResult.setCode(400001);
				sendResult.setMsg("删除失败");
				sendResult.setData(null);
			}
		}else {
			sendResult.setCode(400001);
			sendResult.setMsg("操作失败,请先删除下级部门");
			sendResult.setData(null);
		}
		return sendResult.toString();
	}
}
